package org.example.ui;

import org.example.objects.Question;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
import java.util.Timer;

public class AnswerFrame extends JFrame implements ActionListener {

    private JLabel havePassedLabel;
    private JLabel rightNumLabel;
    private JLabel totalTimeLabel;
    private JLabel scoreLabel;
    private JTextPane questionArea;
    private JPanel answerArea;
    private JCheckBox optionA;
    private JCheckBox optionB;
    private JCheckBox optionC;
    private JCheckBox optionD;
    private JLabel countDownClock;
    private JLabel displayResult;
    private JButton submit;
    private JButton restart;
    private JButton exit;

    //现在抽取到的题目数组的下标值
    private Integer currentQuestionIndex;
    //答对的题目数
    private Integer correctAnswers;
    //已答题
    private Integer totalQuestions;
    //总时间
    private Integer totalTime;
    //题库
    private List<Question> questionBank;
    //选择到的题
    private List<Question> selectedQuestions;
    //倒计时
    private Integer countDownTime;
    //倒计时计时器
    private Timer timer;

    public AnswerFrame() {
        initFrame();

        initView();

        initializeQuestionBank();

        startExam();

        this.setVisible(true);
    }

    private void initializeQuestionBank() {
        questionBank = new ArrayList<>();
        // 添加至少20道多选题，每题10分
        questionBank.add(new Question("卡门涡街广泛存在于高楼、高塔、桥墩等物体后面，其主要危害是（ ）",
                "A. 横向振荡频率与物体固有频率接近",
                "B. 横向作用力较大",
                "C. 纵向振荡频率与物体固有频率接近",
                "D. 纵向作用力较大",
                "A"));
        questionBank.add(new Question("卡门涡街可以在哪些物体形态中产生？（ ）",
                "A. 等离子体",
                "B. 液体",
                "C. 气体",
                "D. 固体",
                "BC"));
        questionBank.add(new Question("COMSOL软件采用的主要原理有（ ）",
                "A. 解析方法",
                "B. 有限元方法",
                "C. 数值方法",
                "D. 多物理场耦合",
                "BCD"));
        questionBank.add(new Question("本实验中卡门涡街的涡旋频率与哪些因素有关？（ ）",
                "A. 雷诺数",
                "B. 流体流速",
                "C. 流体密度",
                "D. 圆柱半径",
                "ABD"));
        questionBank.add(new Question("以下属于消除卡门涡街效应的例子有（ ）",
                "A. 在高塔上安装接地线",
                "B. 在烟囱外侧安装螺旋形隔板",
                "C. 在摩天大楼内安装阻尼器",
                "D. 在吊桥侧面留有风洞",
                "BCD"));
        questionBank.add(new Question("卡门涡街形成的直接原因是（ ）",
                "A. 涡旋间的非线性左右",
                "B. 涡旋的周期性脱落",
                "C. 障碍物的对称分布",
                "D. 流体的均匀流动",
                "B"));
        questionBank.add(new Question("下面哪个是描述不可压缩流体的方程（ ）",
                "A. 拉格朗日公式",
                "B. 伯努利方程",
                "C. 郎之万方程",
                "D. 克拉伯龙方程",
                "B"));
        questionBank.add(new Question("本实验中圆柱体受到的升力的方向（ ）",
                "A. 沿涡旋脱落方向",
                "B. 垂直于流体流动方向",
                "C. 沿圆柱方向",
                "D. 沿流体流动方向",
                "B"));
        questionBank.add(new Question("本实验中流体的雷诺数为（ ）",
                "A. 300",
                "B. 100",
                "C. 200",
                "D. 50",
                "B"));
        questionBank.add(new Question("本实验的建模和研究的问题属于（ ）",
                "A. 三维模型、瞬态",
                "B. 二维模型、瞬态",
                "C. 三维模型、稳态",
                "D. 二维模型、稳态",
                "B"));
        questionBank.add(new Question("建模时使圆柱体略偏离长方形的中心，原因是（ ）",
                "A. 为了达到稳态",
                "B. 为了使涡旋脱落",
                "C. 为了防止湍流",
                "D. 为了触发涡旋",
                "D"));
        questionBank.add(new Question("实验中计算升力系数和曳力系数时的积分对象是（ ）",
                "A. 长方形壁的受力",
                "B. 流体的速度",
                "C. 圆柱的受力",
                "D. 流体的受力",
                "C"));
        questionBank.add(new Question("本实验的实验目的是（ ）",
                "A. 模拟圆柱体的振动频率",
                "B. 了解卡门涡街的基础知识",
                "C. 用Comsol软件模拟卡门涡街",
                "D. 学习Comsol软件的使用",
                "BCD"));
        questionBank.add(new Question("通过输出狭缝记录不同波长光的输出信号强度的光谱仪又称为（ ）",
                "A. 光栅单色仪",
                "B. 光栅散射仪",
                "C. 光栅衍射仪",
                "D. 光栅复色仪",
                "A"));
        questionBank.add(new Question("关于光栅的分辨本领R和角色散D，下面说法正确的是（ ）",
                "A. R反比于光谱级次k，正比于光栅刻痕N",
                "B. D正比与光谱级次k，反比于光栅常数d",
                "C. R正比于光谱级次k和光栅刻痕N",
                "D. D正比于光谱级次k和光栅常数d",
                "BC"));
        questionBank.add(new Question("本实验所用光谱仪的光学系统包括（ ）",
                "A. 准光镜",
                "B. 接收器",
                "C. 衍射光栅",
                "D. 入射和出射狭缝",
                "ABCD"));
        questionBank.add(new Question("Question 17?", "A", "B", "C", "D", "A"));
        questionBank.add(new Question("Question 18?", "A", "B", "C", "D", "A"));
        questionBank.add(new Question("Question 19?", "A", "B", "C", "D", "A"));
        questionBank.add(new Question("Question 20?", "A", "B", "C", "D", "A"));

        // 随机选择10道题
        selectedQuestions = new ArrayList<>(questionBank);
        Collections.shuffle(selectedQuestions);
        selectedQuestions = selectedQuestions.subList(0, 10);
    }

    private void startExam() {
        currentQuestionIndex = 0;
        correctAnswers = 0;
        totalQuestions = 0;
        totalTime = 0;
        countDownTime = 10;

        showQuestion(selectedQuestions.get(currentQuestionIndex));

    }

    private void submitAnswer() {
        if(currentQuestionIndex>=10)
        {
            return;
        }
        Question currentQuestion = selectedQuestions.get(currentQuestionIndex);

        JCheckBox checkBoxA = (JCheckBox) answerArea.getComponent(0);
        JCheckBox checkBoxB = (JCheckBox) answerArea.getComponent(1);
        JCheckBox checkBoxC = (JCheckBox) answerArea.getComponent(2);
        JCheckBox checkBoxD = (JCheckBox) answerArea.getComponent(3);

        String userAnswer = "";
        if (checkBoxA.isSelected()) userAnswer += "A";
        if (checkBoxB.isSelected()) userAnswer += "B";
        if (checkBoxC.isSelected()) userAnswer += "C";
        if (checkBoxD.isSelected()) userAnswer += "D";

        if (userAnswer.equals(currentQuestion.getCorrectAnswer())) {
            correctAnswers++;
            displayResult.setText("答案正确");
        }
        else
        {
            displayResult.setText("答案错误");
        }
        displayResult.setVisible(true);

        Timer displayTimer = new Timer();
        displayTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                displayResult.setVisible(false);
                nextQuestion();
                displayTimer.cancel();  // 取消定时器
            }
        }, 1000);
    }

    private void showQuestion(Question question) {
        restart.setEnabled(true);
        submit.setEnabled(true);
        exit.setEnabled(true);

        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                countDownTime--;
                totalTime++;
                if(countDownTime == 0)
                {
                    submitAnswer();
                }
                countDownClock.setText("倒计时："+countDownTime+"s");
                totalTimeLabel.setText("总时间: "+totalTime+"s");
                countDownClock.repaint();
            }
        }, 0, 1000); // 每隔1秒执行一次

        //每次新题目的展示，刷新页面
        havePassedLabel.setText("已答题："+totalQuestions+"/10");
        rightNumLabel.setText("答对题数："+correctAnswers);
        scoreLabel.setText("成绩："+correctAnswers*10);
        totalTimeLabel.setText("总时间："+totalTime+"s");

        questionArea.setText(question.getText());

        optionA.setText(question.getOptionA());
        optionB.setText(question.getOptionB());
        optionC.setText(question.getOptionC());
        optionD.setText(question.getOptionD());

        this.repaint();
    }

    private void nextQuestion() {
        //这只是跳转过程，在这里进行数据的处理
        restart.setEnabled(false);
        submit.setEnabled(false);
        exit.setEnabled(false);
        optionA.setSelected(false);
        optionB.setSelected(false);
        optionC.setSelected(false);
        optionD.setSelected(false);

//        displayResult.setVisible(false)
        timer.cancel();
        totalQuestions++;
        countDownTime = 10;
        currentQuestionIndex++;
        if (currentQuestionIndex < selectedQuestions.size()) {
            showQuestion(selectedQuestions.get(currentQuestionIndex));
        } else {
            finishExam();
        }
    }

    private void finishExam() {
        timer.cancel();
        restart.setEnabled(false);
        submit.setEnabled(false);
        exit.setEnabled(false);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        this.dispose();
        new TerminateFrame(correctAnswers*10);
    }

    private void initView() {
        havePassedLabel = new JLabel("已答题；7/10");
        havePassedLabel.setBounds(30,10,100,50);
        havePassedLabel.setOpaque(true);
        //havePassedLabel.setBackground(Color.black);
        this.getContentPane().add(havePassedLabel);

        rightNumLabel = new JLabel("答对题数；3");
        rightNumLabel.setBounds(140,10,100,50);
        rightNumLabel.setOpaque(true);
        //rightNumLabel.setBackground(Color.black);
        this.getContentPane().add(rightNumLabel);

        scoreLabel = new JLabel("成绩：70");
        scoreLabel.setBounds(250,10,100,50);
        scoreLabel.setOpaque(true);
        //scoreLabel.setBackground(Color.black);
        this.getContentPane().add(scoreLabel);

        totalTimeLabel = new JLabel("总时间：76s");
        totalTimeLabel.setBounds(360,10,100,50);
        totalTimeLabel.setOpaque(true);
        //scoreLabel.setBackground(Color.black);
        this.getContentPane().add(totalTimeLabel);

        questionArea = new JTextPane();
        questionArea.setText("卡门涡街形成的直接原因是（ ）");
        questionArea.setBounds(50,80,400,250);
        questionArea.setEditable(false);
        questionArea.setOpaque(false);
        questionArea.setCaret(null);


        this.getContentPane().add(questionArea);

        answerArea = new JPanel();
        answerArea.setBounds(30,340,440,250);
        answerArea.setLayout(new GridLayout(4,0));
        optionA = new JCheckBox("A. 涡旋间的非线性左右");
        optionB = new JCheckBox("B. 电子从材料表面逸出所需的最小能量");
        optionC = new JCheckBox("C. 障碍物的对称分布");
        optionD = new JCheckBox("D. 流体的均匀流动");
        answerArea.add(optionA);
        answerArea.add(optionB);
        answerArea.add(optionC);
        answerArea.add(optionD);


        this.getContentPane().add(answerArea);

        countDownClock = new JLabel("倒计时：8s");
        countDownClock.setBounds(60,600,100,40);
        countDownClock.setOpaque(true);
        //countDownClock.setBackground(Color.black);
        this.getContentPane().add(countDownClock);

        displayResult = new JLabel("答案正确");
        displayResult.setVisible(false);
        displayResult.setForeground(Color.RED);
        displayResult.setBounds(370,600,100,40);
        displayResult.setOpaque(true);
        //countDownClock.setBackground(Color.black);
        this.getContentPane().add(displayResult);

        submit = new JButton("提交");
        submit.setBounds(60,650,100,40);
        this.getContentPane().add(submit);
        submit.addActionListener(this);

        restart = new JButton("重新开始");
        restart.setBounds(200,650,100,40);
        this.getContentPane().add(restart);
        restart.addActionListener(this);


        exit = new JButton("终止答题");
        exit.setBounds(340,650,100,40);
        this.getContentPane().add(exit);
        exit.addActionListener(this);

    }

    private void initFrame() {
        this.setSize(500,750);
        this.setLayout(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setAlwaysOnTop(true);
        this.setLocationRelativeTo(null);
        this.setTitle("Java 机考");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == restart)
        {
            this.dispose();
            new StartFrame();
        }
        else if(e.getSource() == submit)
        {
            submitAnswer();
        }
        else if(e.getSource() == exit)
        {
            this.dispose();
            new TerminateFrame(correctAnswers*10);
        }
    }
}
